<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>未定义行为</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/ub","wgTitle":"cpp/language/ub","wgCurRevisionId":63392,"wgArticleId":7735,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":[],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/ub","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><style type="text/css">/*<![CDATA[*/
.source-text {line-height: normal;}
.source-text li, .source-text pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for text
 * CSS class: source-text, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.text.source-text .de1, .text.source-text .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.text.source-text  {font-family:monospace;}
.text.source-text .imp {font-weight: bold; color: red;}
.text.source-text li, .text.source-text .li1 {font-weight: normal; vertical-align:top;}
.text.source-text .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.text.source-text .li2 {font-weight: bold; vertical-align:top;}
.text.source-text .ln-xtra, .text.source-text li.ln-xtra, .text.source-text div.ln-xtra {background-color: #ffc;}
.text.source-text span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_ub skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">未定义行为</h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em;">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="https://zh.cppreference.com/w/cpp/container" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="basic_concepts.html" title="cpp/language/basic concepts">基本概念</a><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="">
<tr class="t-nv"><td colspan="5"> <a href="../keywords.html" title="cpp/keyword"> 语言关键词</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="translation_phases.html" title="cpp/language/translation phases"> 翻译阶段</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../comments.html" title="cpp/comment"> 注释</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="main_function.html" title="cpp/language/main function"> <code>main()</code> 函数</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="name.html" title="cpp/language/identifiers"> 名字和标识符</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="incomplete_type.html" title="cpp/language/type"> 类型</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="types.html" title="cpp/language/types"> 基础类型</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="object.html" title="cpp/language/object"> 对象</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="scope.html" title="cpp/language/scope"> 作用域</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="lifetime.html" title="cpp/language/lifetime"> 对象生存期</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="storage_duration.html" title="cpp/language/storage duration"> 存储期与连接</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="definition.html" title="cpp/language/definition"> 定义和单一定义规则（ODR）</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="lookup.html" title="cpp/language/lookup"> 名字查找</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="qualified_lookup.html" title="cpp/language/qualified lookup"> 有限定名字查找</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="unqualified_lookup.html" title="cpp/language/unqualified lookup"> 无限定名字查找</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="as_if.html" title="cpp/language/as if"> “如同”规则</a></td></tr>
<tr class="t-nv"><td colspan="5"> <strong class="selflink"> 未定义行为</strong></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="memory_model.html" title="cpp/language/memory model"> 内存模型</a> </td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>若违反某些规则，则令整个程序失去意义。
</p>
<h3><span class="mw-headline" id=".E8.A7.A3.E9.87.8A">解释</span></h3>
<p>C++ 标准为不被归入下列分类之一的每个程序都精确定义了其<a href="as_if.html" title="cpp/language/as if">可观察行为</a>：
</p>
<ul><li> <i>非良构（ill-formed）</i>——程序拥有语法错误或可诊断的语义错误。遵从标准的 C++ 编译器必须为此给出诊断，即使它定义了为这种代码赋予了含义的语言扩展（例如用非常量长度数组）也应如此。标准文本用 <i>shall（应当）</i>、 <i>shall not（不应当）</i>和 <i>ill-formed（非良构）</i>给出了这些要求。
</li><li> <i>非良构而不要求诊断（ill-formed no diagnostic required）</i>——程序拥有通常情况下可能无法诊断的语义错误（例如 <a href="definition.html" title="cpp/language/definition">ODR</a> 的违规或者其他只能在连接时检测的错误）。若执行这种程序则行为未定义。
</li><li> <i>由实现定义的行为（implementation-defined behavior）</i>——程序的行为随实现而变动，遵从标准的实现必须为每个这样的行为的效果提供文档。例如 <span class="t-lc"><a href="../types/size_t.html" title="cpp/types/size t">std::size_t</a></span> 的类型或字节中的位数，或者 <span class="t-lc"><a href="../memory/new/bad_alloc.html" title="cpp/memory/new/bad alloc">std::bad_alloc::what</a></span> 的文本。由实现定义的行为的一个子集是<i>本地环境特定行为（locale-specific behavior）</i>，它取决于实现所提供的<a href="../locale.html" title="cpp/locale">本地环境</a>。
</li><li> <i>未指明的行为（ unspecified behavior ）</i>——程序的行为随实现而变动，而不要求遵从标准的实现为每个行为的效果提供文档。例如<a href="eval_order.html" title="cpp/language/eval order">求值顺序</a>，等同的<a href="string_literal.html" title="cpp/language/string literal">字符串字面量</a>是否为相异对象，数组分配的开销，等等。每个未指明行为均产生合法结果集合中的一个结果。
</li><li> <i>未定义行为（undefined behavior，UB）</i>——对程序的行为无任何限制。未定义行为的例子是数组边界外的内存访问，有符号整数溢出，空指针的解引用，在表达式中对同一标量<a href="eval_order.html" title="cpp/language/eval order">多于一次</a>的<span class="t-rev-inl t-until-cxx11"><span>中间无序列点</span> <span><span class="t-mark-rev t-until-cxx11">(C++11 前)</span></span></span><span class="t-rev-inl t-since-cxx11"><span>无序</span> <span><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></span></span>的修改，通过<a href="reinterpret_cast.html#.E7.B1.BB.E5.9E.8B.E5.88.AB.E5.90.8D.E5.8C.96" title="cpp/language/reinterpret cast">不同类型的指针</a>访问对象，等等。不要求编译器诊断未定义行为（尽管许多简单情形确实会得到诊断），而且不要求所编译的程序做任何有意义的事。
</li></ul>
<h3><span class="mw-headline" id="UB_.E4.B8.8E.E4.BC.98.E5.8C.96">UB 与优化</span></h3>
<p>因为正确的 C++ 程序不含未定义行为，故在启用优化选项以编译确实含有 UB 的程序时，编译器可能产生不期待的结果：
</p><p>例如，
</p>
<h4><span class="mw-headline" id=".E6.9C.89.E7.AC.A6.E5.8F.B7.E6.BA.A2.E5.87.BA">有符号溢出</span></h4>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw4">int</span> foo<span class="br0">(</span><span class="kw4">int</span> x<span class="br0">)</span> <span class="br0">{</span>
    <span class="kw1">return</span> x<span class="sy2">+</span><span class="nu0">1</span> <span class="sy1">&gt;</span> x<span class="sy4">;</span> <span class="co1">// 要么为 true 要么因有符号溢出而致 UB</span>
<span class="br0">}</span></pre></div></div>
<p>可编译为（<a rel="nofollow" class="external text" href="https://godbolt.org/z/y4vIi1">演示</a>）
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1">foo<span class="br0">(</span><span class="kw4">int</span><span class="br0">)</span><span class="sy4">:</span>
        movl    $<span class="nu19">1</span>, <span class="sy2">%</span>eax
        ret</pre></div></div>
<p><br>
</p>
<h4><span class="mw-headline" id=".E8.BE.B9.E7.95.8C.E5.A4.96.E8.AE.BF.E9.97.AE">边界外访问</span></h4>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw4">int</span> table<span class="br0">[</span><span class="nu0">4</span><span class="br0">]</span> <span class="sy1">=</span> <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span>
<span class="kw4">bool</span> exists_in_table<span class="br0">(</span><span class="kw4">int</span> v<span class="br0">)</span>
<span class="br0">{</span>
    <span class="co1">// 在头 4 次迭代中返回 true，或因边界外访问而致 UB</span>
    <span class="kw1">for</span> <span class="br0">(</span><span class="kw4">int</span> i <span class="sy1">=</span> <span class="nu0">0</span><span class="sy4">;</span> i <span class="sy1">&lt;=</span> <span class="nu0">4</span><span class="sy4">;</span> i<span class="sy2">++</span><span class="br0">)</span> <span class="br0">{</span>
        <span class="kw1">if</span> <span class="br0">(</span>table<span class="br0">[</span>i<span class="br0">]</span> <span class="sy1">==</span> v<span class="br0">)</span> <span class="kw1">return</span> <span class="kw2">true</span><span class="sy4">;</span>
    <span class="br0">}</span>
    <span class="kw1">return</span> <span class="kw2">false</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>可能编译为（<a rel="nofollow" class="external text" href="https://godbolt.org/z/e2bC84">演示</a>）
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1">exists_in_table<span class="br0">(</span><span class="kw4">int</span><span class="br0">)</span><span class="sy4">:</span>
        movl    $<span class="nu19">1</span>, <span class="sy2">%</span>eax
        ret</pre></div></div>
<h4><span class="mw-headline" id=".E6.9C.AA.E5.88.9D.E5.A7.8B.E5.8C.96.E6.A0.87.E9.87.8F">未初始化标量</span></h4>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><a href="../types/size_t.html"><span class="kw100">std::<span class="me2">size_t</span></span></a> f<span class="br0">(</span><span class="kw4">int</span> x<span class="br0">)</span>
<span class="br0">{</span>
    <a href="../types/size_t.html"><span class="kw100">std::<span class="me2">size_t</span></span></a> a<span class="sy4">;</span>
    <span class="kw1">if</span><span class="br0">(</span>x<span class="br0">)</span> <span class="co1">// x 非零或 UB</span>
        a <span class="sy1">=</span> <span class="nu0">42</span><span class="sy4">;</span>
    <span class="kw1">return</span> a<span class="sy4">;</span> 
<span class="br0">}</span></pre></div></div>
<p>可能编译为（<a rel="nofollow" class="external text" href="https://godbolt.org/z/QYZvsl">演示</a>）
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1">f<span class="br0">(</span><span class="kw4">int</span><span class="br0">)</span><span class="sy4">:</span>
        mov     eax, <span class="nu0">42</span>
        ret</pre></div></div>
<div class="t-example"><p>以下给出的输出曾在旧版本 gcc 上观察到</p><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw4">bool</span> p<span class="sy4">;</span> <span class="co1">// 未初始化局部变量</span>
<span class="kw1">if</span><span class="br0">(</span>p<span class="br0">)</span> <span class="co1">// UB ：访问未初始化标量</span>
    <a href="../io/c/puts.html"><span class="kw1830">std::<span class="me2">puts</span></span></a><span class="br0">(</span><span class="st0">"p is true"</span><span class="br0">)</span><span class="sy4">;</span>
<span class="kw1">if</span><span class="br0">(</span><span class="sy3">!</span>p<span class="br0">)</span> <span class="co1">// UB ：访问未初始化标量</span>
    <a href="../io/c/puts.html"><span class="kw1830">std::<span class="me2">puts</span></span></a><span class="br0">(</span><span class="st0">"p is false"</span><span class="br0">)</span><span class="sy4">;</span></pre></div></div>
<p>可能的输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">p is true
p is false</pre></div></div> 
</div>
<h4><span class="mw-headline" id=".E9.9D.9E.E6.B3.95.E6.A0.87.E9.87.8F">非法标量</span></h4>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw4">int</span> f<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
  <span class="kw4">bool</span> b <span class="sy1">=</span> <span class="kw2">true</span><span class="sy4">;</span>
  <span class="kw4">unsigned</span> <span class="kw4">char</span><span class="sy2">*</span> p <span class="sy1">=</span> <span class="kw1">reinterpret_cast</span><span class="sy1">&lt;</span><span class="kw4">unsigned</span> <span class="kw4">char</span><span class="sy2">*</span><span class="sy1">&gt;</span><span class="br0">(</span><span class="sy3">&amp;</span>b<span class="br0">)</span><span class="sy4">;</span>
  <span class="sy2">*</span>p <span class="sy1">=</span> <span class="nu0">10</span><span class="sy4">;</span>
  <span class="co1">// 从 b 读取现在是 UB</span>
  <span class="kw1">return</span> b <span class="sy1">==</span> <span class="nu0">0</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>可编译成（<a rel="nofollow" class="external text" href="https://gcc.godbolt.org/z/6itUO1">演示</a>）
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1">f<span class="br0">(</span><span class="br0">)</span><span class="sy4">:</span>
        movl    $<span class="nu19">11</span>, <span class="sy2">%</span>eax
        ret</pre></div></div>
<h4><span class="mw-headline" id=".E7.A9.BA.E6.8C.87.E9.92.88.E8.A7.A3.E5.BC.95.E7.94.A8">空指针解引用</span></h4>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw4">int</span> foo<span class="br0">(</span><span class="kw4">int</span><span class="sy2">*</span> p<span class="br0">)</span> <span class="br0">{</span>
    <span class="kw4">int</span> x <span class="sy1">=</span> <span class="sy2">*</span>p<span class="sy4">;</span>
    <span class="kw1">if</span><span class="br0">(</span><span class="sy3">!</span>p<span class="br0">)</span> <span class="kw1">return</span> x<span class="sy4">;</span> <span class="co1">// 要么如上产生 UB，要么不可能采用此分支</span>
    <span class="kw1">else</span> <span class="kw1">return</span> <span class="nu0">0</span><span class="sy4">;</span>
<span class="br0">}</span>
<span class="kw4">int</span> bar<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
    <span class="kw4">int</span><span class="sy2">*</span> p <span class="sy1">=</span> nullptr<span class="sy4">;</span>
    <span class="kw1">return</span> <span class="sy2">*</span>p<span class="sy4">;</span>        <span class="co1">// 无条件 UB</span>
<span class="br0">}</span></pre></div></div>
<p>可能编译为（ <a rel="nofollow" class="external text" href="https://godbolt.org/z/kzr8VJ">foo 用 gcc 、 bar 用 clang</a> ）
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1">foo<span class="br0">(</span><span class="kw4">int</span><span class="sy2">*</span><span class="br0">)</span><span class="sy4">:</span>
        xorl    <span class="sy2">%</span>eax, <span class="sy2">%</span>eax
        ret
bar<span class="br0">(</span><span class="br0">)</span><span class="sy4">:</span>
        retq</pre></div></div>
<h4><span class="mw-headline" id=".E8.AE.BF.E9.97.AE.E5.B7.B2.E4.BC.A0.E9.80.92.E7.BB.99_realloc_.E7.9A.84.E6.8C.87.E9.92.88">访问已传递给 realloc 的指针</span></h4>
<div class="t-example"><p>选择 clang 以观察所示输出</p><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
<span class="co2">#include &lt;cstdlib&gt;</span>
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
    <span class="kw4">int</span> <span class="sy2">*</span>p <span class="sy1">=</span> <span class="br0">(</span><span class="kw4">int</span><span class="sy2">*</span><span class="br0">)</span><a href="../memory/c/malloc.html"><span class="kw759">std::<span class="me2">malloc</span></span></a><span class="br0">(</span>sizeof<span class="br0">(</span><span class="kw4">int</span><span class="br0">)</span><span class="br0">)</span><span class="sy4">;</span>
    <span class="kw4">int</span> <span class="sy2">*</span>q <span class="sy1">=</span> <span class="br0">(</span><span class="kw4">int</span><span class="sy2">*</span><span class="br0">)</span><a href="../memory/c/realloc.html"><span class="kw762">std::<span class="me2">realloc</span></span></a><span class="br0">(</span>p, sizeof<span class="br0">(</span><span class="kw4">int</span><span class="br0">)</span><span class="br0">)</span><span class="sy4">;</span>
    <span class="sy2">*</span>p <span class="sy1">=</span> <span class="nu0">1</span><span class="sy4">;</span> <span class="co1">// UB ：访问传递给 realloc 的指针</span>
    <span class="sy2">*</span>q <span class="sy1">=</span> <span class="nu0">2</span><span class="sy4">;</span>
    <span class="kw1">if</span> <span class="br0">(</span>p <span class="sy1">==</span> q<span class="br0">)</span> <span class="co1">// UB ：访问传递给 realloc 的指针</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="sy2">*</span>p <span class="sy1">&lt;&lt;</span> <span class="sy2">*</span>q <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>可能的输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">12</pre></div></div> 
</div>
<h4><span class="mw-headline" id=".E6.97.A0.E5.89.AF.E4.BD.9C.E7.94.A8.E7.9A.84.E6.97.A0.E9.99.90.E5.BE.AA.E7.8E.AF">无副作用的无限循环</span></h4>
<div class="t-example"><p>选择 clang 以观察所示输出</p><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
 
<span class="kw4">int</span> fermat<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
  <span class="kw4">const</span> <span class="kw4">int</span> MAX <span class="sy1">=</span> <span class="nu0">1000</span><span class="sy4">;</span>
  <span class="kw4">int</span> a<span class="sy1">=</span><span class="nu0">1</span>,b<span class="sy1">=</span><span class="nu0">1</span>,c<span class="sy1">=</span><span class="nu0">1</span><span class="sy4">;</span>
  <span class="co1">// 无副作用的无限循环是 UB</span>
  <span class="kw1">while</span> <span class="br0">(</span><span class="nu0">1</span><span class="br0">)</span> <span class="br0">{</span>
    <span class="kw1">if</span> <span class="br0">(</span><span class="br0">(</span><span class="br0">(</span>a<span class="sy2">*</span>a<span class="sy2">*</span>a<span class="br0">)</span> <span class="sy1">==</span> <span class="br0">(</span><span class="br0">(</span>b<span class="sy2">*</span>b<span class="sy2">*</span>b<span class="br0">)</span><span class="sy2">+</span><span class="br0">(</span>c<span class="sy2">*</span>c<span class="sy2">*</span>c<span class="br0">)</span><span class="br0">)</span><span class="br0">)</span><span class="br0">)</span> <span class="kw1">return</span> <span class="nu0">1</span><span class="sy4">;</span>
    a<span class="sy2">++</span><span class="sy4">;</span>
    <span class="kw1">if</span> <span class="br0">(</span>a<span class="sy1">&gt;</span>MAX<span class="br0">)</span> <span class="br0">{</span> a<span class="sy1">=</span><span class="nu0">1</span><span class="sy4">;</span> b<span class="sy2">++</span><span class="sy4">;</span> <span class="br0">}</span>
    <span class="kw1">if</span> <span class="br0">(</span>b<span class="sy1">&gt;</span>MAX<span class="br0">)</span> <span class="br0">{</span> b<span class="sy1">=</span><span class="nu0">1</span><span class="sy4">;</span> c<span class="sy2">++</span><span class="sy4">;</span> <span class="br0">}</span>
    <span class="kw1">if</span> <span class="br0">(</span>c<span class="sy1">&gt;</span>MAX<span class="br0">)</span> <span class="br0">{</span> c<span class="sy1">=</span><span class="nu0">1</span><span class="sy4">;</span><span class="br0">}</span>
  <span class="br0">}</span>
  <span class="kw1">return</span> <span class="nu0">0</span><span class="sy4">;</span>
<span class="br0">}</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
  <span class="kw1">if</span> <span class="br0">(</span>fermat<span class="br0">(</span><span class="br0">)</span><span class="br0">)</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"Fermat's Last Theorem has been disproved.<span class="es1">\n</span>"</span><span class="sy4">;</span>
  <span class="kw1">else</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"Fermat's Last Theorem has not been disproved.<span class="es1">\n</span>"</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>可能的输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">Fermat's Last Theorem has been disproved.</pre></div></div> 
</div>
<h3><span class="mw-headline" id=".E5.A4.96.E9.83.A8.E9.93.BE.E6.8E.A5">外部链接</span></h3>
<ul><li> <a rel="nofollow" class="external text" href="http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html">每个 C 程序员都该知道关于未定义行为的事 #1/3</a>
</li><li> <a rel="nofollow" class="external text" href="http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html">每个 C 程序员都该知道关于未定义行为的事 #2/3</a>
</li><li> <a rel="nofollow" class="external text" href="http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html">每个 C 程序员都该知道关于未定义行为的事 #3/3</a>
</li><li> <a rel="nofollow" class="external text" href="http://blogs.msdn.com/b/oldnewthing/archive/2014/06/27/10537746.aspx">未定义行为能导致时间旅行（在所有事项中，时间旅行可是最惊人的）</a>
</li><li> <a rel="nofollow" class="external text" href="http://www.cs.utah.edu/~regehr/papers/overflow12.pdf">了解 C/C++ 中的整数溢出</a>
</li><li> <a rel="nofollow" class="external text" href="http://kukuruku.co/hub/cpp/undefined-behavior-and-fermats-last-theorem">未定义行为与费马最后定理</a>
</li><li> <a rel="nofollow" class="external text" href="http://lwn.net/Articles/342330/">空指针的趣事，第一部分</a> （ Linux 2.6.30 中空指针解引用所致的未定义行为所引发的局部滥用）
</li></ul>
<h3><span class="mw-headline" id=".E5.8F.82.E9.98.85">参阅</span></h3>
<table class="t-dsc-begin">

</table>

<!-- 
NewPP limit report
Preprocessor visited node count: 1178/1000000
Preprocessor generated node count: 3816/1000000
Post‐expand include size: 33415/2097152 bytes
Template argument size: 7543/2097152 bytes
Highest expansion depth: 13/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:7735-0!*!0!!zh!*!zh!* and timestamp 20191220084617 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/ub&amp;oldid=63392">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/ub&amp;oldid=63392</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/ub">Online version</a></li><li>Offline version retrieved 2020-03-14 18:00.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2019年12月19日 (星期四) 22:09。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过8,377次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 1.005 secs. -->
	</body>
<!-- Cached 20191220084617 -->
</html>